﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Resources;
using System.Xml;
using System.Xml.Linq;
using Com.CodePlex.SPPower.Model;
using System.Xml.XPath;

namespace Com.CodePlex.SPPower.Data {

	public class CmdRepository {

		public IList<object> FindRootItems() {
			IList<object> result = new List<object>();
			if (File.Exists(Properties.Settings.Default.File_Categories)) {
				XElement root = XDocument.Load(Properties.Settings.Default.File_Categories).Root;
				result = (
					root
					.Elements("category")
					.Select(i => (object)new CmdCategory {
						Name = i.Attribute("name").Value,
						Href = i.Attribute("href").Value
					})
				).Union(
					root
					.Elements("command")
					.Select(i => (object)new Cmd {
						Name = i.Attribute("name").Value,
						Href = i.Attribute("href").Value
					})
				).ToList();
			}
			return result;
		}

		public IList<object> FindCategoryItems(CmdCategory item) {
			IList<object> result = new List<object>();
			if (File.Exists(Properties.Settings.Default.File_Categories)) {
				XElement root = XDocument.Load(Properties.Settings.Default.File_Categories).Root;
				((IEnumerable)root.XPathEvaluate("//category[@name='" + item.Name + "']")).Cast<XElement>().ToList().ForEach(i => {
					(
						i
						.Elements("category")
						.Select(j => (object)new CmdCategory {
							Name = j.Attribute("name").Value,
							Href = j.Attribute("href").Value
						})
					).Union(
						i
						.Elements("command")
						.Select(j => (object)new Cmd {
							Name = j.Attribute("name").Value,
							Href = j.Attribute("href").Value
						})
					).ToList().ForEach(j => {
						result.Add(j);
					});
				});
			}
			return result;
		}

		public IList<string> FindCommandsWithCategory() {
			IList<string> result = new List<string>();
			if (File.Exists(Properties.Settings.Default.File_Categories)) {
				XElement root = XDocument.Load(Properties.Settings.Default.File_Categories).Root;
				((IEnumerable)root.XPathEvaluate("//command")).Cast<XElement>().ToList().ForEach(i => {
					result.Add(i.Attribute("name").Value);
				});
			}
			return result;
		}
	}
}